<?php

namespace server\dao;

use common\helpers\BaseHelper;
use Yii;
use yii\db\Query;

/**
 * This is the model class for table "sys_login_log".
 *
 * @property int    $id
 * @property string $app_id     系统id
 * @property int    $user_id    用户id
 * @property string $username   昵称
 * @property int    $type       类型。1登录，2退出
 * @property string $ip         ip地址
 * @property int    $created_at 创建时间
 */
class SysLoginLog_bak extends \common\core\server\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'sys_login_log';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['app_id', 'user_id', 'username', 'type', 'ip'], 'required'],
            [['user_id', 'created_at'], 'integer'],
            [['app_id', 'username'], 'string', 'max' => 32],
            [['ip'], 'string', 'max' => 15],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'app_id'     => '系统id',
            'user_id'    => '用户id',
            'username'   => '昵称',
            'type'       => '类型。1登录，2退出',
            'ip'         => 'ip地址',
            'created_at' => '创建时间',
        ];
    }

    /**
     * 获得 登录日志
     *
     * @param array $params
     *
     * @return mixed
     */
    public function getLoginLog(array $params)
    {
        $query = new Query();
        $query->from($this->tableName());

        if ($this->issetAndEmpty($params, 'app_id')) {
            $query->andWhere(['like', 'app_id', $params['app_id']]);
        }

        if ($this->issetAndEmpty($params, 'username')) {
            $query->andWhere(['like', 'username', $params['username']]);
        }

        if ($this->issetAndEmpty($params, 'type')) {
            $query->andWhere(['type' => $params['type']]);
        }

        /*if ($this->issetAndEmpty($params, 'created_at')) {
            $time = BaseHelper::formattingDoubleDate($params['created_at']);
            $query->andWhere(['between', 'created_at', $time[0], $time[1]]);
        }*/
        if ($this->issetAndEmpty($params, 'startTime')) {
            $query->andWhere(['>=', 'created_at', $params['startTime']]);
        }
        if ($this->issetAndEmpty($params, 'endTime')) {
            $query->andWhere(['<=', 'created_at', $params['endTime']]);
        }
        $query->orderBy('created_at desc');

        //$this->order($query, 'created_at desc');
        return $this->page($query);
    }

    /**
     * 登录 日志
     *
     * @param array $params
     *
     * @return mixed
     * @throws
     */
    public function setUserLoginLog(array $params)
    {
        $log = new SysLoginLog();
        $log->setAttributes($params);
        $log->save();
        return $log;
    }

    /**
     * table name
     *
     * @return mixed
     */
    public function table()
    {
        return '系统登录日志';
    }
}
